package cn.sirun.com.fca.account.view.impl;

import android.app.Activity;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v7.app.AppCompatActivity;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.widget.TextView;

import com.tencent.cloud.iov.kernel.constant.StatusCode;
import com.tencent.cloud.iov.kernel.model.BaseResponse;
import com.tencent.cloud.iov.kernel.service.TXStorageService;
import com.tencent.cloud.iov.router.Router;
import com.tencent.cloud.iov.util.ActivityUtils;
import com.tencent.cloud.iov.util.FragmentUtils;
import com.tencent.cloud.iov.util.SHAUtils;
import com.tencent.cloud.iov.util.storage.TXCacheManager;
import com.tencent.cloud.uikit.ui.widget.IovToolbar;
import com.tencent.cloud.uikit.utils.DialogUtils;
import com.tencent.cloud.uikit.utils.SystemUiUtils;
import com.tencent.tac.storage.StorageResultListener;
import com.tencent.tac.storage.TACStorageReference;
import com.tencent.tac.storage.TACStorageTaskSnapshot;

import java.io.File;

import cn.sirun.com.fca.account.R;
import cn.sirun.com.fca.account.constant.AccountActivityConst;
import cn.sirun.com.fca.account.constant.AccountCommonConst;
import cn.sirun.com.fca.account.constant.AccountIntentConst;
import cn.sirun.com.fca.account.constant.RequestParamConst;
import cn.sirun.com.fca.account.fragment.CameraFragment;
import cn.sirun.com.fca.account.fragment.ConfirmInfoFragment;
import cn.sirun.com.fca.account.fragment.OperateFragment;
import cn.sirun.com.fca.account.model.bind.RecognizePicRequest;
import cn.sirun.com.fca.account.model.bind.RecognizePicResponse;
import cn.sirun.com.fca.account.model.bind.SubmitCarInfoRequest;
import cn.sirun.com.fca.account.model.bind.SubmitOwnerInfoRequest;
import cn.sirun.com.fca.account.presenter.IAuthenticationPresenter;
import cn.sirun.com.fca.account.presenter.impl.AuthenticationPresenter;
import cn.sirun.com.fca.account.uitl.AccountStatusUtils;
import cn.sirun.com.fca.account.uitl.IntentUtils;
import cn.sirun.com.fca.account.uitl.StorageUtils;
import cn.sirun.com.fca.account.view.IAuthenticationView;

/**
 * @author vinsonhuang
 * @date 2018/5/4
 */
public class AuthenticationFlowView extends AccountBaseLoadingFlowView<IAuthenticationPresenter>
        implements IAuthenticationView {

    private static final String TAG = AuthenticationFlowView.class.getSimpleName();

    private IovToolbar mToolbar;

    private FragmentManager mFragmentManager;

    private Fragment mCurrentFragment;

    private OperateFragment mOperateFragment;

    private CameraFragment mCameraFragment;

    private ConfirmInfoFragment mConfirmInfoFragment;

    private String mUrl = null;

    /**
     * 当前处理的证件照片路径
     */
    private String mFilePath;

    /**
     * 当前处理的证件照片类型
     */
    private RequestParamConst.PictureTypeEnum mPictureType;

    private boolean isReviewAuthInfo = false;

    private boolean isAddVehicle = false;

    String mFlagPicUrl = "";

    private boolean mFlagFirstPic = false;
    private boolean mFlagVersoPic = false;
    private boolean mFlagInHand = false;

    RecognizePicResponse mRecognizePicResponse;
    private String mDin;

    public AuthenticationFlowView(final Activity activity) {
        super(activity);
        mToolbar = SystemUiUtils.showActionBar(activity, null);
        mToolbar.setHomeAsUpListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                activity.onBackPressed();
            }
        });
    }

    @Override
    protected IAuthenticationPresenter createPresenter() {
        return new AuthenticationPresenter();
    }

    @Override
    public void onCreate() {
        super.onCreate();
        mFragmentManager = ((AppCompatActivity) getActivity()).getSupportFragmentManager();
        initView(R.layout.authentication_activity);
    }

    @Override
    public void onRecognizePicResult(BaseResponse<RecognizePicResponse> response) {
        handleRecognizeResponse(response);
    }

//    @Override
//    public void onSubmitCarInfoResult(BaseResponse<CarInfo> response) {
//        hideLoadingView();
//        int code = response.getCode();
//        if (StatusCode.SUCCESS == response.getCode()) {
//            // 上传成功后，置空url
//            mUrl = null;
//            TXCacheManager.getInstance().put(AccountCommonConst.START_ACTIVATE_CAR_ID,
//                    response.getData().getCarId());
//            if (!isAddVehicle) {
//                turnToBindActivity(mPictureType);
//            } else {
//                turnToRelevanceActivity();
//            }
//            return;
//        }
//        AccountStatusUtils.showToast(getActivity(), code, "上传失败");
//    }

    @Override
    public void onSubmitOwnerInfoResult(BaseResponse<Void> response) {
        hideLoadingView();
        int code = response.getCode();
        if (StatusCode.SUCCESS == code) {
            // 上传成功后，置空url
            mUrl = null;
            // 清空缓存的证件信息
            StorageUtils.removeAuthInfo(mPictureType);
            turnToBindActivity(mPictureType);
            return;
        }
        AccountStatusUtils.showToast(getActivity(), code, "上传失败");
        StorageUtils.removeAuthInfo(mPictureType);
    }

    @Override
    public void onSubmitOwnerImgResult(BaseResponse<RecognizePicResponse> result) {
        hideLoadingView();
        if(result.getData() != null){
            mRecognizePicResponse = new RecognizePicResponse();
            mRecognizePicResponse.setAddress(result.getData().getAddress());
            mRecognizePicResponse.setId(result.getData().getId());
            mRecognizePicResponse.setName(result.getData().getName());
            mRecognizePicResponse.setSex(result.getData().getSex());
        }


    }

    public void setAuthTitle(RequestParamConst.PictureTypeEnum pictureType) {
        if (RequestParamConst.PictureTypeEnum.IDENTITY_CARD == pictureType) {
//            mToolbar.setTitle("个人信息");
            final Activity activity = getActivity();
            final IovToolbar toolbar = SystemUiUtils.showActionBar(
                    activity, "");
            toolbar.setHomeAsUpText(R.string.tv_title_upback);

        } else {
            mToolbar.setTitle("车辆信息");
        }
    }

    public void setAuthTitle(String title) {
        mToolbar.setTitle(title);
    }

    public void setAuthImage(String filePath) {
        if (null != mOperateFragment && mOperateFragment.isVisible()) {
            mOperateFragment.setImageView(filePath);
        }
    }

    private void initView(int viewId) {
        setContentView(viewId);
        Intent intent = getActivity().getIntent();
        mDin = intent.getStringExtra("din");
        RequestParamConst.PictureTypeEnum pictureType;
        int from = IntentUtils.getIntentFrom(intent, AccountIntentConst.VEHICLE_AUTHENTICATION);
        isReviewAuthInfo = IntentUtils.isReviewAuthInfo(intent, false);
        isAddVehicle = IntentUtils.isAddVehicle(intent, false);
        if (AccountIntentConst.VEHICLE_AUTHENTICATION == from) {
            pictureType = RequestParamConst.PictureTypeEnum.VEHICLE_LICENSE;
        } else {
            pictureType = RequestParamConst.PictureTypeEnum.IDENTITY_CARD;
        }
        mPictureType = pictureType;
        if (isReviewAuthInfo) {
            turnToConfirmInfoFragment(null, false);
        } else {
            turnToOperateFragment(null, false);
        }
    }

    private void turnToOperateFragment(String filePath, boolean isBack) {
        mFilePath = filePath;

        if (null == mOperateFragment) {
            mOperateFragment = OperateFragment.newInstance(mPictureType, filePath);
            mOperateFragment.setOperateListener(new OperateFragment.OnOperateListener() {
                @Override
                public void onManualInputCallback(TextView textView) {
//                    mFilePath = null;
//                    turnToConfirmInfoFragment(null, false);

                    if(mFlagFirstPic && mFlagVersoPic && mFlagInHand){
                        Intent intent = Router.fromPath(AccountActivityConst.Path.OWNER_BELONGTO_CAR);
                        intent.putExtra("personinfo",mRecognizePicResponse);
                        intent.putExtra("din",mDin);
                        ActivityUtils.startActivity(getActivity(), intent);
//                        textView.setBackgroundResource(R.drawable.s_btn_bg_border);
                    }else{

                    }


                }

                @Override
                public void onTakePhotoCallback() {
//                    final BottomSheetDialog bottomSheetDialog
//                            = new BottomSheetDialog(getActivity());
//                    View.OnClickListener listener = new View.OnClickListener() {
//                        @Override
//                        public void onClick(View v) {
//                            int id = v.getId();
//                            if (R.id.btn_take_photo == id) {
//                                turnToCameraFragment(false);
//                            } else if (R.id.btn_photo_album == id) {
//                                ActivityUtils.openAlbum(getActivity(),
//                                        AccountCommonConst.PHOTO_FROM_ALBUM_REQUEST_CODE);
//                            }
//                            bottomSheetDialog.dismiss();
//                        }
//                    };
//                    bottomSheetDialog.setClickListener(listener);
//                    bottomSheetDialog.show();

                    /**
                     * 直接跳转拍照页面
                     */
                    mFlagPicUrl = "0";
                    turnToCameraFragment(false);
                }

                @Override
                public void onTakePhotoCallbackTwo() {


                    /**
                     * 直接跳转拍照页面反面照
                     */
                    mFlagPicUrl = "1";
                    turnToCameraFragment(false);
                }

                @Override
                public void onTakePhotoCallbackThree() {


                    /**
                     * 直接跳转拍照页面反面照
                     */
                    mFlagPicUrl = "2";
                    turnToCameraFragment(false);
                }

                @Override
                public void onSubmitCallback(String filePath) {
                    mFilePath = filePath;
                    // 上传图片
                    uploadData();
                    showLoadingView();
                }
            });
        }

        mOperateFragment.setFilePath(filePath);
        if (switchFragment(mOperateFragment, isBack)) {
            /**
             * 0为正面照 1为反面照 2为手持照
             */

            if(mFlagPicUrl.equals("0")){
                mOperateFragment.updateView("0");
            }else if(mFlagPicUrl.equals("1")){
                mOperateFragment.updateView("1");
            }else if(mFlagPicUrl.equals("2")){
                mOperateFragment.updateView("2");
            }
//            mOperateFragment.updateView();

            mFilePath = filePath;
            // 上传图片
            uploadData();
            showLoadingView();

        }
        setAuthTitle(mPictureType);
    }

    private void turnToCameraFragment(boolean isBack) {
        if (null == mCameraFragment) {
            mCameraFragment = new CameraFragment();
            mCameraFragment.setCameraListener(new CameraFragment.OnCameraListener() {
                @Override
                public void onTakePictureCallback(String filePath) {
                    turnToOperateFragment(filePath, true);
                }

                @Override
                public void onBackPressed() {
                    turnToOperateFragment(null, true);
                }
            });
        }
        mCameraFragment.setPictureType(mPictureType);
        if (switchFragment(mCameraFragment, isBack)) {
            mCameraFragment.checkPermissionOrStartPreview();
        }
        setAuthTitle(mPictureType);
    }

    private void turnToConfirmInfoFragment(BaseResponse<RecognizePicResponse> response,
                                           boolean isBack) {
        if (null == mConfirmInfoFragment) {
            mConfirmInfoFragment = new ConfirmInfoFragment();
            mConfirmInfoFragment.setConfirmListener(new ConfirmInfoFragment.OnConfirmListener() {
                @Override
                public void onConfirmCallback(String url, String ownerOrName,
                                              String vehicleIdentityNumber,
                                              String engineIdOrIdentity) {
                    if (RequestParamConst.PictureTypeEnum.VEHICLE_LICENSE == mPictureType) {
                        SubmitCarInfoRequest request = new SubmitCarInfoRequest();
                        request.setOwner(ownerOrName);
                        request.setCarNumber(vehicleIdentityNumber);
                        request.setEngineId(engineIdOrIdentity);
                        if (TextUtils.isEmpty(url)) {
                            request.setUrl(mUrl);
                        } else {
                            request.setUrl(url);
                        }
//                        getPresenter().submitCarInfo(request);
                    } else {
                        SubmitOwnerInfoRequest request = new SubmitOwnerInfoRequest();
                        request.setName(ownerOrName);
                        request.setId(engineIdOrIdentity);
                        if (TextUtils.isEmpty(url)) {
                            request.setUrl(mUrl);
                        } else {
                            request.setUrl(url);
                        }
                        getPresenter().submitOwnerInfo(request);
                    }
                    showLoadingView();
                }


                @Override
                public void onBackPressed() {
                    if (isReviewAuthInfo) {
                        turnToBindActivity(mPictureType);
                    } else {
                        turnToOperateFragment(mFilePath, true);
                    }
                }
            });
        }
        Bundle bundle = new Bundle();
        bundle.putBoolean(AccountIntentConst.IS_REVIEW_AUTH_INFO, isReviewAuthInfo);
        mConfirmInfoFragment.setArguments(bundle);
        mConfirmInfoFragment.setInitData(response, mPictureType);

        if (switchFragment(mConfirmInfoFragment, isBack)) {
            mConfirmInfoFragment.updateView();
        }
        setAuthTitle("个人认证");
    }

    private void turnToBindActivity(RequestParamConst.PictureTypeEnum pictureType) {
        Intent intent = Router.fromPath(AccountActivityConst.Path.VEHICLE_BIND);
        if (RequestParamConst.PictureTypeEnum.VEHICLE_LICENSE == pictureType) {
            intent.putExtra(AccountIntentConst.FROM, AccountIntentConst.VEHICLE_AUTHENTICATION);
        } else {
            intent.putExtra(AccountIntentConst.FROM, AccountIntentConst.REAL_NAME_CERTIFICATION);
        }
        intent.putExtra(AccountIntentConst.IS_REVIEW_AUTH_INFO, isReviewAuthInfo);
        ActivityUtils.backToPreActivity(getActivity(), intent);
    }

    private void turnToRelevanceActivity() {
        Intent intent = Router.fromPath(AccountActivityConst.Path.RELEVANCE);
        intent.putExtra(AccountIntentConst.IS_ADD_VEHICLE, isAddVehicle);
        ActivityUtils.startActivityForResult(getActivity(), intent);
    }

    private void uploadData() {
        // 上传监听器
        StorageResultListener<TACStorageTaskSnapshot> listener = new
                StorageResultListener<TACStorageTaskSnapshot>() {

                    @Override
                    public void onSuccess(TACStorageTaskSnapshot tacStorageTaskSnapshot) {
                        // 组装图片url
                        TACStorageReference ref = tacStorageTaskSnapshot.getStorage();
                        AuthenticationFlowView.this.mUrl = new StringBuilder("https://")
                                .append(ref.getBucket())
                                .append(".cos.")
                                .append(ref.getRegion())
                                .append(".myqcloud.com")
                                .append(File.separator)
                                .append(ref.getPath())
                                .toString();

                        Log.e("xqm","图片地址"+AuthenticationFlowView.this.mUrl);
                        /**
                         * 如果不调用图片识别接口，就直接调用上传个人证件照接口
                         */
                        SubmitOwnerInfoRequest subRequest = new SubmitOwnerInfoRequest();
                        subRequest.setUrl(AuthenticationFlowView.this.mUrl);
                        if(mFlagPicUrl.equals("0")){

                            mFlagFirstPic = true;
                            subRequest.setPicType("0");

                            // 调用图片识别接口
                            if (null == getPresenter()) {
                                createPresenter();
                            }
                            RecognizePicRequest request = new RecognizePicRequest();
                            request.setUrl(AuthenticationFlowView.this.mUrl);
                            request.setType(mPictureType.getValue());
                            getPresenter().recognizePic(request);


                        }else if(mFlagPicUrl.equals("1")){
                            mFlagVersoPic = true;
                            subRequest.setPicType("1");
                        }else if(mFlagPicUrl.equals("2")){
                            mFlagInHand = true;
                            subRequest.setPicType("2");
                        }

                        /**
                         * 按钮显示红色
                         */
                        if(mFlagFirstPic && mFlagVersoPic && mFlagInHand){
                            mOperateFragment.updateTextBg("0");
                        }

                        getPresenter().submitOwnerImg(subRequest);



                    }

                    @Override
                    public void onFailure(TACStorageTaskSnapshot tacStorageTaskSnapshot) {
                        if (null != tacStorageTaskSnapshot) {
                            tacStorageTaskSnapshot.getError().printStackTrace();
                        }
                        //取消拍照
//                        handleUploadOrRecognizeFailed();
                        hideLoadingView();
                    }
                };

        int fileType = RequestParamConst.ProFileOperateEnum.UPLOAD_PROFILE.getValue();
        String fileSHA256 = SHAUtils.sha256OfFile(mFilePath);

        // 上传图片
        TXStorageService.getInstance().uploadFile(fileType, fileSHA256, mFilePath, listener);
    }

    private void handleRecognizeResponse(BaseResponse<RecognizePicResponse> response) {
        hideLoadingView();
        if (StatusCode.SUCCESS == response.getCode()) {
            mFlagFirstPic = true;
            mOperateFragment.setButtonClickable(true);
//            turnToConfirmInfoFragment(response, false);
            AccountStatusUtils.showToast(getActivity(), 0, "识别成功");
            return;
        }else if(response.getCode() == 12016){

        }else{
            mFlagFirstPic = false;
            handleUploadOrRecognizeFailed();
        }

    }

    private void handleUploadOrRecognizeFailed() {
        DialogUtils.showDialog(getActivity(), R.string.dialog_title_error_message,
                R.string.upload_recognize_photo_failed,
                R.string.upload_recognize_photo_cancle,
                R.string.upload_recognize_photo_affirm,
                new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        dialog.dismiss();
                    }
                }, new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        dialog.dismiss();
                        AuthenticationFlowView.this.mUrl = null;
//                        turnToConfirmInfoFragment(null, false);
                    }
                });
        mOperateFragment.setButtonClickable(true);
    }

    private boolean switchFragment(Fragment fragment, boolean isBack) {
        boolean isAdded = fragment.isAdded();
        FragmentUtils.showFragment(mFragmentManager, mCurrentFragment,
                fragment, R.id.fl_vehicle_container, isBack);
        mCurrentFragment = fragment;
        return isAdded;
    }
}
